package com.whsxt.common.updata;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.whsxt.common.util.FileUpdateUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;

@RequestMapping("/update")
@RestController
public class UpdataController {
	/**
	 * 	文件上传
	 * @param mf
	 * @return
	 */
	@RequestMapping("/up")
	public Map<String, Object> up(MultipartFile mf) {
		//获取上传的文件名
		String oldName = mf.getOriginalFilename();
		//获取上传文件名的后缀
		String suffix = oldName.substring(oldName.lastIndexOf("."),oldName.length());
		String newName = IdUtil.simpleUUID() + suffix +"_temp";
		//照片分天  每天的照片创建一个文件夹
		String date = DateUtil.format(new Date(), "yyyy-MM-dd");
		File file = new File(FileUpdateUtil.diskPath, date);
		if(!file.exists()) {
			file.mkdirs();
		}
		// 最终写入的文件位置
		File finalPath = new File(file, newName);
		try {
			mf.transferTo(finalPath);
		}  catch (IOException e) {
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("path", date+"/"+newName);
		return map;
	}
	
	/**
	 * 	文件下载
	 * @param path
	 * @return
	 */
	@RequestMapping("/down")
	public ResponseEntity<Object> down(String path) {
		File file = new File(FileUpdateUtil.diskPath, path);
		if(file.exists()) {
			byte[] bs = null;
			bs = FileUtil.readBytes(file);
			//创建封装响应头信息的对象
			HttpHeaders header=new HttpHeaders();
			//封装响应内容类型(APPLICATION_OCTET_STREAM 响应的内容不限定)
			header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			//设置下载的文件的名称
//			header.setContentDispositionFormData("attachment", "123.jpg");
			//创建ResponseEntity对象
			ResponseEntity<Object> entity= new ResponseEntity<Object>(bs, header, HttpStatus.CREATED);
			return entity;
		}
		return null;
	}
	
}
